<template>
  <div class="task-assign-container">
    <!-- 任务信息 -->
    <div class="task-info-card" v-if="task">
      <h3 class="task-title">{{ task.task_title }}</h3>
      <div class="task-meta">
        <div class="meta-item">
          <van-icon name="team" size="14" />
          <span>{{ task.team?.name || '未知队伍' }}</span>
        </div>
        <div class="meta-item">
          <van-icon name="clock-o" size="14" />
          <span>{{ formatDate(task.deadline) || '无截止日期' }}</span>
        </div>
        <div :class="['priority-badge', `priority-${task.priority}`]">
          {{ getPriorityText(task.priority) }}
        </div>
      </div>
    </div>

    <!-- 成员列表 -->
    <div class="member-list-container">
      <div class="section-header">
        <span class="section-title">队伍成员</span>
        <span class="selected-count">已选择 {{ selectedMemberIds.length }} 人</span>
      </div>
      <div class="member-list" v-if="teamMembers.length > 0">
        <div
          v-for="member in teamMembers"
          :key="member.id"
          :class="['member-item', { selected: selectedMemberIds.includes(member.id) }]"
          @click="toggleMember(member.id)"
        >
          <div class="member-avatar">
            <img :src="member.avatarUrl || '/default-avatar.png'" alt="头像" />
          </div>
          <div class="member-info">
            <div class="member-name">{{ member.username }}</div>
            <div class="member-role">{{ getMemberRoleText(member.userRole || 0) }}</div>
            <div class="member-stats">
              <span>待处理: {{ getMemberTaskCount(member.id, 0) }}</span>
              <span>进行中: {{ getMemberTaskCount(member.id, 1) }}</span>
            </div>
          </div>
          <div class="member-checkbox" :class="{ checked: selectedMemberIds.includes(member.id) }">
            <van-icon v-if="selectedMemberIds.includes(member.id)" name="success" color="#1989fa" />
          </div>
        </div>
      </div>
      <div v-else class="empty-members">
        <van-empty description="暂无成员" />
      </div>
    </div>

    <!-- 推荐成员 -->
    <div class="recommend-section" v-if="recommendedMembers.length > 0">
      <div class="section-header">
        <span class="section-title">推荐成员</span>
        <span class="recommend-tip">（基于当前任务负载）</span>
      </div>
      <div class="recommend-list">
        <div
          v-for="member in recommendedMembers"
          :key="member.id"
          :class="['recommend-item', { selected: selectedMemberIds.includes(member.id) }]"
          @click="toggleMember(member.id)"
        >
          <div class="member-avatar-small">
            <img :src="member.avatarUrl || '/default-avatar.png'" alt="头像" />
          </div>
          <span class="member-name">{{ member.username }}</span>
          <span class="task-count">{{ getMemberTaskCount(member.id, 0) }} 个待处理</span>
        </div>
      </div>
    </div>

    <!-- 底部操作栏 -->
    <div class="bottom-action">
      <div class="confirm-btn" @click="handleConfirm">确定</div>
    </div>

    <!-- 底部提示 -->
    <div class="bottom-tip" v-if="showTip">
      <van-icon name="info-o" color="#faad14" />
      <span>请至少选择一名负责人</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { showToast } from 'vant';
import { taskStore } from '../stores/task/task';
import { userStore } from '../stores/user/user';
import { teamStore } from '../stores/team/team';
import type { Task } from '../models/task';

const router = useRouter();
const route = useRoute();
const taskStoreAPI = taskStore();
const userStoreAPI = userStore();
const teamStoreAPI = teamStore();

// 状态管理
const taskId = computed(() => Number(route.params.id));
const task = ref<Task | null>(null);
const teamMembers = ref<any[]>([]);
const selectedMemberIds = ref<number[]>([]);
const memberTaskCounts = ref<Map<number, Map<number, number>>>(new Map());
const showTip = ref(false);

// 计算属性
const recommendedMembers = computed(() => {
  // 根据待处理任务数量排序，优先推荐任务少的成员
  return [...teamMembers.value]
    .sort((a, b) => {
      const countA = getMemberTaskCount(a.id, 0);
      const countB = getMemberTaskCount(b.id, 0);
      return countA - countB;
    })
    .slice(0, 3);
});

// 辅助函数
const getPriorityText = (priority: number) => {
  const map = { 1: '低', 2: '中', 3: '高' };
  return map[priority as keyof typeof map] || '未知';
};

const getMemberRoleText = (role: number) => {
  const map = { 0: '普通成员', 1: '管理员', 2: '队长' };
  return map[role as keyof typeof map] || '成员';
};

const formatDate = (dateStr?: string) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

const getMemberTaskCount = (memberId: number, status: number) => {
  const memberMap = memberTaskCounts.value.get(memberId);
  return memberMap?.get(status) || 0;
};

// 成员选择相关函数
const toggleMember = (memberId: number) => {
  const index = selectedMemberIds.value.indexOf(memberId);
  if (index > -1) {
    selectedMemberIds.value.splice(index, 1);
  } else {
    selectedMemberIds.value.push(memberId);
  }
  showTip.value = false;
};

const handleConfirm = async () => {
  if (selectedMemberIds.value.length === 0) {
    showTip.value = true;
    return;
  }

  try {
    const res = await taskStoreAPI.assignTask(taskId.value, selectedMemberIds.value);
    if (res.code === 200) {
      showToast('分配成功');
      router.back();
    } else {
      showToast('分配失败');
    }
  } catch (error) {
    showToast('分配失败');
  }
};

// 加载数据函数
const loadTaskDetail = async () => {
  try {
    const res = await taskStoreAPI.fetchTaskDetail(taskId.value);
    if (res.code === 200) {
      task.value = res.data;
      // 初始化已选负责人
      if (task.value.assigneeList && task.value.assigneeList.length > 0) {
        selectedMemberIds.value = task.value.assigneeList.map((a: any) => a.id);
      }
      // 加载队伍成员
      if (task.value.team_id) {
        await loadTeamMembers(task.value.team_id);
        await loadMemberTaskCounts(task.value.team_id);
      }
    } else {
      showToast('获取任务详情失败');
      router.back();
    }
  } catch (error) {
    showToast('获取任务详情失败');
    router.back();
  }
};

const loadTeamMembers = async (teamId: number) => {
  try {
    const res = await teamStoreAPI.getTeamMembers(teamId);
    if (res.code === 200) {
      teamMembers.value = res.data || [];
    }
  } catch (error) {
    console.error('获取队伍成员失败:', error);
  }
};

const loadMemberTaskCounts = async (teamId: number) => {
  try {
    const res = await taskStoreAPI.fetchTaskList({ teamId, page: 1, pageSize: 100 });
    if (res.code === 200) {
      const tasks = res.data.list || [];
      // 初始化任务计数Map
      teamMembers.value.forEach(member => {
        const statusMap = new Map<number, number>();
        statusMap.set(0, 0); // 待处理
        statusMap.set(1, 0); // 进行中
        memberTaskCounts.value.set(member.id, statusMap);
      });
      
      // 统计每个成员的任务数量
      tasks.forEach((task: Task) => {
        if (task.assigneeList) {
          task.assigneeList.forEach((assignee: any) => {
            const memberMap = memberTaskCounts.value.get(assignee.id);
            if (memberMap) {
              const currentCount = memberMap.get(task.status) || 0;
              memberMap.set(task.status, currentCount + 1);
            }
          });
        }
      });
    }
  } catch (error) {
    console.error('获取成员任务数量失败:', error);
  }
};

// 初始化
onMounted(async () => {
  const currentUser = await userStoreAPI.getCurrentUser();
  if (!currentUser) {
    showToast('请先登录');
    router.push('/login');
    return;
  }
  await loadTaskDetail();
});
</script>

<style scoped>
.task-assign-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 70px; /* 为底部操作栏留出空间 */
}

.task-info-card {
  background-color: #fff;
  padding: 16px;
  margin-bottom: 10px;
}

.task-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
}

.task-meta {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.meta-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666;
}

.meta-item .van-icon {
  margin-right: 4px;
}

.priority-badge {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.priority-1 {
  background-color: #f0f9ff;
  color: #1989fa;
}

.priority-2 {
  background-color: #fff7e6;
  color: #faad14;
}

.priority-3 {
  background-color: #fff1f0;
  color: #f5222d;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #fff;
  margin-bottom: 1px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.selected-count {
  font-size: 12px;
  color: #666;
}

.recommend-tip {
  font-size: 12px;
  color: #999;
}

.member-list-container {
  background-color: #fff;
  margin-bottom: 10px;
}

.member-list {
  max-height: 400px;
  overflow-y: auto;
}

.member-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f5f5f5;
}

.member-item:last-child {
  border-bottom: none;
}

.member-item.selected {
  background-color: #f0f9ff;
}

.member-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 12px;
}

.member-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.member-info {
  flex: 1;
}

.member-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.member-role {
  font-size: 12px;
  color: #999;
  margin-bottom: 6px;
}

.member-stats {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #666;
}

.member-checkbox {
  width: 24px;
  height: 24px;
  border: 1px solid #ddd;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.member-checkbox.checked {
  background-color: #1989fa;
  border-color: #1989fa;
}

.member-checkbox.checked .van-icon {
  color: #fff;
}

.recommend-section {
  background-color: #fff;
  padding: 16px;
  margin-bottom: 10px;
}

.recommend-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 12px;
}

.recommend-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background-color: #f5f5f5;
  border-radius: 16px;
  font-size: 14px;
}

.recommend-item.selected {
  background-color: #e8f4ff;
  border: 1px solid #1989fa;
}

.member-avatar-small {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 8px;
}

.member-avatar-small img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.task-count {
  margin-left: 8px;
  font-size: 12px;
  color: #666;
}

.empty-members {
  padding: 40px 0;
}

/* 底部操作栏 */
.bottom-action {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 12px 16px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
  border-top: 1px solid #eee;
}

.confirm-btn {
  width: 100%;
  padding: 12px;
  background-color: #1989fa;
  color: #fff;
  text-align: center;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 500;
}

.bottom-tip {
  position: fixed;
  bottom: 80px; /* 调整提示位置，在操作栏上方 */
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: #fff;
  padding: 8px 16px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  font-size: 14px;
}

.bottom-tip .van-icon {
  margin-right: 6px;
}
</style>